import React, { useState, useEffect } from "react";
import {
  StyleSheet,
  View,
  Image,
  TouchableOpacity,
  Dimensions,
  ScrollView,
  ActivityIndicator,
  Alert,
} from "react-native";
import { useRouter, useFocusEffect } from "expo-router";
import { MaterialCommunityIcons } from "@expo/vector-icons";
import { useCallback } from "react";

import { ThemedText } from "@/components/ThemedText";
import { ThemedView } from "@/components/ThemedView";
import { Colors } from "@/constants/Colors";
import { useColorScheme } from "@/hooks/useColorScheme";
import { matchAPI } from "@/services/matchAPI";

// 模拟匹配用户数据
const MATCH_DATA = [
  {
    id: "1",
    name: "李大爷",
    age: 70,
    location: "北京市海淀区",
    bio: "退休教师，喜欢下棋、打太极和养花。希望找到志同道合的朋友一起度过美好时光。",
    interests: ["下棋", "太极", "园艺"],
    avatar: { uri: "https://randomuser.me/api/portraits/men/72.jpg" },
    distance: "0.5km",
    compatibility: 95,
  },
  {
    id: "2",
    name: "张阿姨",
    age: 65,
    location: "北京市朝阳区",
    bio: "退休护士，热爱生活，喜欢跳广场舞、烹饪和旅游。希望能认识新朋友，分享生活乐趣。",
    interests: ["广场舞", "烹饪", "旅游"],
    avatar: { uri: "https://randomuser.me/api/portraits/women/65.jpg" },
    distance: "1.2km",
    compatibility: 88,
  },
  {
    id: "3",
    name: "王爷爷",
    age: 72,
    location: "北京市西城区",
    bio: "退休工程师，喜欢摄影、钓鱼和听京剧。寻找有共同兴趣的朋友一起交流。",
    interests: ["摄影", "钓鱼", "京剧"],
    avatar: { uri: "https://randomuser.me/api/portraits/men/78.jpg" },
    distance: "2.5km",
    compatibility: 82,
  },
  {
    id: "4",
    name: "刘奶奶",
    age: 68,
    location: "北京市东城区",
    bio: "退休会计，喜欢唱歌、看电影和养宠物。希望能找到聊得来的朋友。",
    interests: ["唱歌", "电影", "宠物"],
    avatar: { uri: "https://randomuser.me/api/portraits/women/68.jpg" },
    distance: "3.0km",
    compatibility: 78,
  },
  {
    id: "5",
    name: "赵叔叔",
    age: 67,
    location: "北京市丰台区",
    bio: "退休司机，喜欢打乒乓球、下象棋和种菜。想找朋友一起锻炼身体。",
    interests: ["乒乓球", "象棋", "种菜"],
    avatar: { uri: "https://randomuser.me/api/portraits/men/67.jpg" },
    distance: "4.2km",
    compatibility: 75,
  },
];

const { width } = Dimensions.get("window");

export default function MatchScreen() {
  const colorScheme = useColorScheme();
  const router = useRouter();
  const tintColor = Colors[colorScheme ?? "light"].tint;

  const [currentIndex, setCurrentIndex] = useState(0);
  const [likedUsers, setLikedUsers] = useState([]);
  const [recommendations, setRecommendations] = useState([]);
  const [loading, setLoading] = useState(true);
  const [noMoreUsers, setNoMoreUsers] = useState(false);

  // 获取推荐用户
  const fetchRecommendations = async () => {
    try {
      setLoading(true);
      const response = await matchAPI.getRecommendations();
      if (response.data && response.data.length > 0) {
        setRecommendations(response.data);
        setCurrentIndex(0);
        setNoMoreUsers(false);
      } else {
        setNoMoreUsers(true);
      }
    } catch (error) {
      console.error("获取推荐用户失败", error);
      Alert.alert("错误", "获取推荐用户失败，请稍后再试");
    } finally {
      setLoading(false);
    }
  };

  // 初始加载推荐用户
  useEffect(() => {
    fetchRecommendations();
  }, []);

  // 当页面重新获得焦点时刷新推荐用户
  useFocusEffect(
    useCallback(() => {
      console.log('Match screen focused - refreshing recommendations');
      fetchRecommendations();
      return () => {
        // 清理函数，当页面失去焦点时执行
        console.log('Match screen unfocused');
      };
    }, [])
  );

  const currentUser = recommendations[currentIndex];

  const handleLike = async () => {
    if (!currentUser) return;

    try {
      const response = await matchAPI.createMatch(currentUser.id, true);

      // 如果匹配成功，显示提示
      if (response.matched) {
        Alert.alert(
          "匹配成功",
          `你和${currentUser.name}互相喜欢，可以开始聊天了！`,
          [
            { text: "去聊天", onPress: () => router.push("/chat") },
            { text: "继续浏览", onPress: () => {} },
          ]
        );
      }

      setLikedUsers([...likedUsers, currentUser.id]);

      // 移动到下一个用户
      if (currentIndex < recommendations.length - 1) {
        setCurrentIndex(currentIndex + 1);
      } else {
        // 如果已经是最后一个用户，重新获取推荐
        fetchRecommendations();
        setCurrentIndex(0);
      }
    } catch (error) {
      console.error("喜欢用户失败", error);
      Alert.alert("错误", "操作失败，请稍后再试");
    }
  };

  const handleSkip = async () => {
    if (!currentUser) return;

    try {
      // 记录不喜欢
      await matchAPI.createMatch(currentUser.id, false);

      // 移动到下一个用户
      if (currentIndex < recommendations.length - 1) {
        setCurrentIndex(currentIndex + 1);
      } else {
        // 如果已经是最后一个用户，重新获取推荐
        fetchRecommendations();
        setCurrentIndex(0);
      }
    } catch (error) {
      console.error("跳过用户失败", error);
      Alert.alert("错误", "操作失败，请稍后再试");
    }
  };

  const renderInterestItem = (interest, index) => (
    <View key={index} style={styles.interestTag}>
      <ThemedText style={styles.interestText}>{interest}</ThemedText>
    </View>
  );

  return (
    <ThemedView style={styles.container}>
      <View style={styles.header}>
        <ThemedText style={styles.headerTitle}>匹配</ThemedText>
        <TouchableOpacity
          style={styles.filterButton}
          onPress={() => Alert.alert("提示", "匹配偏好设置功能即将上线")}
        >
          <MaterialCommunityIcons
            name='filter-variant'
            size={28}
            color={tintColor}
          />
        </TouchableOpacity>
      </View>

      {loading ? (
        <View style={styles.loadingContainer}>
          <ActivityIndicator size='large' color={tintColor} />
          <ThemedText style={styles.loadingText}>
            正在寻找合适的人...
          </ThemedText>
        </View>
      ) : noMoreUsers ? (
        <View style={styles.noMoreContainer}>
          <MaterialCommunityIcons
            name='emoticon-sad-outline'
            size={80}
            color='#888'
          />
          <ThemedText style={styles.noMoreText}>暂时没有更多推荐啦</ThemedText>
          <ThemedText style={styles.checkLaterText}>稍后再来吧</ThemedText>
        </View>
      ) : currentUser ? (
        <View style={styles.matchCard}>
          <Image
            source={
              currentUser.avatar.uri
                ? currentUser.avatar
                : { uri: currentUser.avatar }
            }
            style={styles.avatar}
          />

          <ScrollView style={styles.userInfoScrollView}>
            <View style={styles.userInfoContainer}>
              <View style={styles.nameAgeContainer}>
                <ThemedText style={styles.nameText}>
                  {currentUser.name}
                </ThemedText>
                <ThemedText style={styles.ageText}>
                  {currentUser.age}岁
                </ThemedText>
              </View>

              <View style={styles.locationContainer}>
                <MaterialCommunityIcons
                  name='map-marker'
                  size={20}
                  color='#888'
                />
                <ThemedText style={styles.locationText}>
                  {currentUser.location}
                </ThemedText>
                <ThemedText style={styles.distanceText}>
                  · {currentUser.distance}
                </ThemedText>
              </View>

              <View style={styles.compatibilityContainer}>
                <MaterialCommunityIcons
                  name='heart-pulse'
                  size={20}
                  color='#FF6B6B'
                />
                <ThemedText style={styles.compatibilityText}>
                  匹配度: {currentUser.compatibility}%
                </ThemedText>
              </View>

              <ThemedText style={styles.bioTitle}>个人简介</ThemedText>
              <ThemedText style={styles.bioText}>{currentUser.bio}</ThemedText>

              <ThemedText style={styles.interestsTitle}>兴趣爱好</ThemedText>
              <View style={styles.interestTags}>
                {currentUser.interests &&
                  currentUser.interests.map(renderInterestItem)}
              </View>
            </View>
          </ScrollView>

          <View style={styles.actionButtons}>
            <TouchableOpacity
              style={[styles.actionButton, styles.skipButton]}
              onPress={handleSkip}
            >
              <MaterialCommunityIcons name='close' size={32} color='#FF6B6B' />
            </TouchableOpacity>
            <TouchableOpacity
              style={[styles.actionButton, styles.likeButton]}
              onPress={handleLike}
            >
              <MaterialCommunityIcons name='heart' size={32} color='#4CAF50' />
            </TouchableOpacity>
          </View>
        </View>
      ) : null}
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    paddingTop: 60,
    paddingBottom: 15,
    paddingHorizontal: 20,
    borderBottomWidth: 1,
    borderBottomColor: "#E1E1E1",
  },
  headerTitle: {
    fontSize: 28,
    fontWeight: "bold",
  },
  filterButton: {
    padding: 5,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  loadingText: {
    marginTop: 15,
    fontSize: 16,
    color: "#888",
  },
  matchCard: {
    flex: 1,
    margin: 15,
    borderRadius: 15,
    backgroundColor: "#FFF",
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 5,
    elevation: 3,
    overflow: "hidden",
    display: "flex",
    flexDirection: "column",
    maxHeight: "90%",
  },
  avatar: {
    width: "100%",
    height: "45%",
    aspectRatio: 16 / 9,
    resizeMode: "cover",
  },
  userInfoScrollView: {
    flex: 1,
    width: "100%",
  },
  userInfoContainer: {
    padding: 15,
    flex: 1,
    overflow: "auto",
  },
  nameAgeContainer: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 5,
  },
  nameText: {
    fontSize: 24,
    fontWeight: "bold",
    marginRight: 10,
  },
  ageText: {
    fontSize: 20,
    color: "#666",
  },
  locationContainer: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 10,
  },
  locationText: {
    fontSize: 16,
    color: "#666",
    marginLeft: 5,
  },
  distanceText: {
    fontSize: 16,
    color: "#888",
    marginLeft: 5,
  },
  compatibilityContainer: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 15,
  },
  compatibilityText: {
    fontSize: 16,
    color: "#FF6B6B",
    marginLeft: 5,
    fontWeight: "500",
  },
  bioTitle: {
    fontSize: 18,
    fontWeight: "bold",
    marginBottom: 5,
  },
  bioText: {
    fontSize: 16,
    lineHeight: 22,
    color: "#444",
    marginBottom: 15,
  },
  interestsTitle: {
    fontSize: 18,
    fontWeight: "bold",
    marginBottom: 10,
  },
  interestTags: {
    flexDirection: "row",
    flexWrap: "wrap",
  },
  interestTag: {
    backgroundColor: "#E8F4F8",
    paddingHorizontal: 15,
    paddingVertical: 8,
    borderRadius: 20,
    marginRight: 10,
    marginBottom: 10,
  },
  interestText: {
    fontSize: 16,
    color: "#0a7ea4",
  },
  actionButtons: {
    flexDirection: "row",
    justifyContent: "space-around",
    paddingVertical: 15,
    borderTopWidth: 1,
    borderTopColor: "#E1E1E1",
    backgroundColor: "#fff",
  },
  actionButton: {
    width: 60,
    height: 60,
    borderRadius: 30,
    justifyContent: "center",
    alignItems: "center",
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 3,
    elevation: 2,
  },
  skipButton: {
    backgroundColor: "#FFF",
    borderWidth: 1,
    borderColor: "#FF6B6B",
  },
  likeButton: {
    backgroundColor: "#FFF",
    borderWidth: 1,
    borderColor: "#4CAF50",
  },
  noMoreContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    padding: 20,
  },
  noMoreText: {
    fontSize: 22,
    fontWeight: "bold",
    marginTop: 20,
    marginBottom: 10,
  },
  checkLaterText: {
    fontSize: 16,
    color: "#888",
  },
});
